package server

import (
	"context"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/protobuf"
	"time"
)

const EVEVT_POINT_FOOTBALL_KEY = "event_point_football"
const EVEVT_POINT_BASKETBALL_KEY = "event_point_baksetball"

var basketCompID = []int{1, 3}                                  // 1 NBA, 3 CBA
var footballCompID = []int{82, 120, 129, 108, 142, 542, 46, 45} // 82:英超 120:西甲 129:德甲 109:意甲 142:法甲 542:中超 46:欧冠 45:欧洲杯

func (s *Server) Compoint(ctx context.Context, req *protobuf.Empty) (*protobuf.CompointListResp, error) {
	var err error

	var fpoint []models_sports.FootballPoint
	err = cache.GetCachedData(EVEVT_POINT_FOOTBALL_KEY, &fpoint)
	if len(fpoint) == 0 {
		err = global.Sport().Model(&models_sports.FootballPoint{}).Where("comp_id in (?)", footballCompID).Order("points desc").Scan(&fpoint).Error
		if err != nil {
			return &protobuf.CompointListResp{}, err
		}
		cache.SetCacheData(EVEVT_POINT_FOOTBALL_KEY, fpoint, 300*time.Second)
	}

	// 最新赛程
	// var scope models_sports.BasketballPoint
	// err = global.Sport().Model(&models_sports.BasketballPoint{}).Order("scope desc").First(&scope).Error
	// if err != nil {
	// 	return &protobuf.CompointListResp{}, err
	// }

	var bpoint []models_sports.BasketballPoint
	cache.GetCachedData(EVEVT_POINT_BASKETBALL_KEY, &bpoint)
	if len(bpoint) == 0 {
		err = global.Sport().Model(&models_sports.BasketballPoint{}).Where("comp_id in (?)", basketCompID).Order("won_rate desc").Scan(&bpoint).Error
		if err != nil {
			return &protobuf.CompointListResp{}, err
		}
		cache.SetCacheData(EVEVT_POINT_BASKETBALL_KEY, bpoint, 300*time.Second)

	}

	var fcomp = []*protobuf.CompFootball{
		{Id: 46, Name: "欧冠"},
		{Id: 82, Name: "英超"},
		{Id: 120, Name: "西甲"},
		{Id: 129, Name: "德甲"},
		{Id: 108, Name: "意甲"},
		{Id: 142, Name: "法甲"},
		{Id: 542, Name: "中超"},
		{Id: 45, Name: "欧洲杯"},
	}

	for idx, v := range fcomp {
		for _, p := range fpoint {
			if p.CompID == int(v.Id) {
				if global.Lang.GetLang() != _const.LangChinese {
					p.TeamName = p.TeamNameEn
				}
				fcomp[idx].Points = append(fcomp[idx].Points, &protobuf.CompFootballPoint{
					TeamId:   int64(p.TeamID),
					TeamName: p.TeamName,
					TeamLogo: p.TeamLogo,
					CompId:   v.Id,
					Won:      int32(p.Won),
					Lost:     int32(p.Loss),
					Draw:     int32(p.Draw),
					Points:   int32(p.Points),
				})
			}
		}
	}

	var bcomp = []*protobuf.CompBasketball{
		{Id: 1, Name: "NBA"},
		{Id: 3, Name: "CBA"},
	}

	for idx, v := range bcomp {
		for _, p := range bpoint {
			if p.CompID == int(v.Id) {
				if global.Lang.GetLang() != _const.LangChinese {
					p.TeamName = p.TeamNameEn
				}
				bcomp[idx].Points = append(bcomp[idx].Points, &protobuf.CompBaksetballPoint{
					TeamId:   int64(p.TeamID),
					TeamName: p.TeamName,
					TeamLogo: p.TeamLogo,
					Won:      int32(p.Won),
					Lost:     int32(p.Lost),
					WonRate:  float32(p.WonRate),
					Area:     p.Name,
					Streak:   p.Streak,
				})
			}
		}
	}

	return &protobuf.CompointListResp{
		Football:   fcomp,
		Basketball: bcomp,
	}, err
}

func (s *Server) PointTeamDetail(ctx context.Context, req *protobuf.PointTeamDetailReq) (*protobuf.PointTeamDetailResp, error) {
	var bmainInfo struct {
		TeamName string `json:"team_name"`
		TeamLogo string `json:"team_logo"`
		Won      int32  `json:"won"`
		Lost     int32  `json:"lost"`
		Rank     int    `json:"rank"`
		// Name     string `json:"name"`
	}
	var fbmainInfo struct {
		TeamName string `json:"team_name"`
		TeamLogo string `json:"team_logo"`
		Won      int32  `json:"won"`
		Loss     int32  `json:"lost"`
		Rank     int    `json:"rank"`
		// Name     string `json:"name"`
	}

	if req.SportId == 1 {
		err := global.Sport().Model(&models_sports.FootballPoint{}).Where("team_name=?", req.Team).Take(&fbmainInfo).Error
		if err != nil {
			return &protobuf.PointTeamDetailResp{}, err
		}
	}
	if req.SportId == 2 {
		err := global.Sport().Model(&models_sports.BasketballPoint{}).Where("team_name=?", req.Team).Take(&bmainInfo).Error
		if err != nil {
			return &protobuf.PointTeamDetailResp{}, err
		}
	}

	// 足球（2024-7月-5月）
	// 篮球（2024-9月-4月）
	var matchesTime int64
	if req.SportId == 1 {
		layout := "2006-01-02 15:04:05"
		timeStr := "2024-07-01 00:00:00"
		t, _ := time.Parse(layout, timeStr)
		matchesTime = t.Unix()
	}
	if req.SportId == 2 {
		layout := "2006-01-02 15:04:05"
		timeStr := "2024-09-01 00:00:00"
		t, _ := time.Parse(layout, timeStr)
		matchesTime = t.Unix()
	}

	var matches []*models_sports.MatchTempSchedule
	err := global.Sport().Model(&models_sports.MatchTempSchedule{}).Where("(home=? or away=?) and sport_id=? and match_time>=?", req.Team, req.Team, req.SportId, matchesTime).Find(&matches).Error
	if err != nil {
		return &protobuf.PointTeamDetailResp{}, err
	}

	var res protobuf.PointTeamDetailResp
	if req.SportId == 1 {
		res.Name = fbmainInfo.TeamName
		res.Logo = fbmainInfo.TeamLogo
		res.Won = fbmainInfo.Won
		res.Lost = fbmainInfo.Loss
		res.Rank = int32(fbmainInfo.Rank)
	}

	if req.SportId == 2 {
		res.Name = bmainInfo.TeamName
		res.Logo = bmainInfo.TeamLogo
		res.Won = bmainInfo.Won
		res.Lost = bmainInfo.Lost
		res.Rank = int32(bmainInfo.Rank)
	}

	var matchIDs []int

	for _, v := range matches {
		matchIDs = append(matchIDs, v.MatchId)
		res.Matches = append(res.Matches, &protobuf.PointTeamMatches{
			Date: v.MatchTime,
			// MatchTitle: mainInfo.Name,
			Home:        v.Home,
			HomeLogo:    v.HomeLogo,
			HomeScore:   int32(v.HomeScore),
			Away:        v.Away,
			AwayLogo:    v.AwayLogo,
			AwayScore:   int32(v.AwayScore),
			MatchId:     int64(v.MatchId),
			Comp:        v.Comp,
			MatchStatus: int32(v.MatchStatus),
		})
	}

	var lives []models_live.Live
	err = global.Live().Where("matchid in (?)", matchIDs).Find(&lives).Error
	if err != nil {
		return &protobuf.PointTeamDetailResp{}, err
	}

	for _, v := range lives {
		for idx, k := range res.Matches {
			if v.Matchid == int(k.MatchId) {
				res.Matches[idx].LiveAnchor = int64(v.Anchorid)
			}
		}
	}

	if req.UserId > 0 {
		var mf []models_sports.MatchFavorite
		err = global.Sport().Where("match_id in (?) and user_id=?", matchIDs, req.UserId).Find(&mf).Error
		if err != nil {
			return &protobuf.PointTeamDetailResp{}, err
		}

		for _, v := range mf {
			for idx, k := range res.Matches {
				if v.MatchId == int(k.MatchId) {
					res.Matches[idx].Fav = true
				}
			}
		}
	}

	return &res, nil
}
